﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net;
using System.Text;
using HtmlAgilityPack;
using System.Text.RegularExpressions;
using Emoney.UserTraining.BLL;
using Emoney.UserTraining.Model;
using Emoney.UserTraining.Cache;

namespace Emoney.UserTraining.Web.OpenMeeting
{
    public partial class open : System.Web.UI.Page
    {
        Traning_NetworkMeetingBLL bll = new Traning_NetworkMeetingBLL();
        List<Traning_NetworkMeeting> lst = new List<Traning_NetworkMeeting>();

        public string sessionkey = "";
        public string sessionId = "";
        public string Gensee_URL = "";

        protected void Page_Load(object sender, EventArgs e)
        {
            string user = Request["name"];
            string mtg_id = "";
            if (Request["mtg_id"] != null && Request["mtg_id"].ToString() != "")
            {
                if (user != "")
                {
                    if (user.Length == 11)
                    {
                        if (user.Substring(0, 2) != "em")
                        {
                            user = user.Substring(0, 3) + "emoney" + user.Substring(7);
                        }
                    }
                }

                mtg_id = Request["mtg_id"].ToString().Trim();
                List<Traning_NetworkMeeting> list = bll.GetList(mtg_id);

                if (list.Count > 0)
                {
                    string before_time = getTimeToStr(list[0].class_date.ToString(), list[0].before_time, -1);
                    string Duration_date = getTimeToStr(list[0].class_date.ToString(), list[0].Duration_date, 1);
                    if ((System.DateTime.Now > Convert.ToDateTime(before_time)) && (Convert.ToDateTime(Duration_date) > System.DateTime.Now))
                    {
                        if (string.IsNullOrEmpty(list[0].Gensee_URL))
                        {
                            int aa = bll.getNetWorkMeetingCache();
                            if (aa <= 0)
                            {
                                aa = getCenwave();
                                bll.addNetWorkMeetingCache(aa);
                            }
                            if (aa < 2000)
                            {
                                string url1 = "http://emoney.cenwave.com/main/user_check_submit.asp?site_id=1062&service_type=0&mtg_id=" + list[0].mtg_id + "&language=Chinese&user_name=" + user + "&mtg_pwd=" + list[0].mtg_password + "";
                                Response.Redirect(url1);
                            }
                            else
                            {
                                Response.Write("<script>alert(\"当前培训教室人数已满，无法进入，请稍后登陆“投资学院”观看相关录像。\")</script>");
                            }
                        }
                        else
                        {
                            if (list[0].Gensee_URL == "1")
                            {
                                Random ro = new Random();

                                string usertype = "8";
                                string StrKey = "Le5&6y!8oPwI";
                                string siteid = "emcps";
                                string flag = "2";
                                string title = StringToUnicode(list[0].mtg_name);
                                string mtgkey = System.DateTime.Now.ToString("yyyyMM") + list[0].mtg_id;
                                string mtgpwd = Convert.ToBase64String(Encoding.Default.GetBytes(GetToStr(list[0].mtg_password))).Replace("/", "_");
                                string hostpwd = Convert.ToBase64String(Encoding.Default.GetBytes(GetToStr(list[0].host_key))).Replace("/", "_");
                                string duration = list[0].Duration_date;
                                string username = StringToUnicode(user);
                                string language = "0";

                                string key = ("meeting" + user + mtg_id.Trim()).Replace(" ", "");
                                News2CacheTools cache = new News2CacheTools();

                                string UserID = cache.Get<string>(key);
                                if (string.IsNullOrEmpty(UserID))
                                {
                                    UserID = ro.Next(10000000).ToString();  //admin
                                    cache.Add(key, UserID, 4, 0, 0);
                                }


                                string timestamp = (System.DateTime.Now - TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1))).TotalMilliseconds.ToString();
                                if (timestamp.Contains("."))
                                    timestamp = timestamp.Split('.')[0];

                                string str = "http://emcps.confcloud.cn/join_mtg.asp?";
                                str += "siteId=" + siteid;   //站点标识
                                str += "&productFlag=" + flag;  //1: 课堂2: 会议
                                str += "&mtgTitle=" + title;  //会议标题
                                str += "&mtgKey=" + mtgkey;
                                str += "&mtgPwd=" + mtgpwd;
                                str += "&hostPwd=" + hostpwd;
                                str += "&duration=" + duration;
                                str += "&userName=" + username;
                                str += "&userId=" + UserID;
                                str += "&userType=" + usertype;
                                str += "&language=" + language;
                                str += "&timestamp=" + timestamp;
                                str += "&authId=" + System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(StrKey + siteid + mtgkey + UserID + usertype + timestamp, "md5");
                                Response.Redirect(str);
                            }
                            else
                            {
                                Gensee_URL = list[0].Gensee_URL + "?token=" + list[0].mtg_password + "&nickName=" + user;
                            }
                        }
                    }
                }
            }
        }

        public string GetToStr(string str)
        {
            string newstr = "";
            Random ro = new Random();
            for (int i = 0; i < str.Length; i++)
            {
                newstr += str.Substring(i, 1) + ro.Next(10);
            }
            return newstr;
        }

        private string StringToUnicode(string srcText)
        {
            string str = "";
            char[] src = srcText.ToCharArray();

            for (int i = 0; i < src.Length; i++)
            {
                byte[] bytes = Encoding.Unicode.GetBytes(src[i].ToString());
                str += Convert.ToInt32(bytes[1].ToString("X2") + bytes[0].ToString("X2"), 16) + ",";
            }
            if (str != "")
            {
                str = str.Substring(0, str.Length - 1);
            }
            return str;
        }

        public int getCenwave()
        {
            string str = returnRUL();
            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(str);
            string xpath = "/html/body/table/tr[2]/td";
            string name = doc.DocumentNode.SelectSingleNode(xpath).InnerHtml;
            name = NoHTML(name);
            int aa = 0;

            if (name.Contains("@"))
            {
                int CenwaveLength = name.Split('@').Length;
                string[] strarr = name.Split('@');

                for (int i = 0; i < CenwaveLength; i++)
                {
                    if (strarr[i] == "admin")
                    {
                        aa += Convert.ToInt32(strarr[i + 1]);
                    }
                }
            }
            return aa;
        }

        public string getTimeToStr(string time, string num, int zf)
        {
            if (time == null || time == "")
            {
                return "";
            }

            if (num == null || num == "")
            {
                return time;
            }
            return Convert.ToDateTime(time).Add(new TimeSpan(0, 0, Convert.ToInt32(num) * zf, 0, 0)).ToString("yyyy-MM-dd HH:mm:ss");
        }

        public string returnRUL()
        {
            string str = "";
            int count = 0;
            string url = "http://emoney.cenwave.com/main/join.asp?site_id=1062&language=Chinese&service_type=0&tel=&random=" + System.DateTime.Now.ToString("yyyyMMddHHmmss");
            string tz = StrToHex("GMT 0800");
            string hexurl = "http://emoney.cenwave.com/getClientTimeZone.asp?tz=" + tz + "&url=" + StrToHex(url);

            while (string.IsNullOrEmpty(sessionId))
            {
                str = LoadData(hexurl); ;
                count++;
                if (count > 5)
                {
                    break;
                }
            }
            if (!string.IsNullOrEmpty(sessionId))
            {
                str = LoadData(hexurl);
            }
            return str;
        }


        public string StrToHex(string str)
        {
            byte[] data = System.Text.Encoding.GetEncoding("utf-8").GetBytes(str);
            StringBuilder sb = new StringBuilder();
            foreach (var c in data)
            {
                sb.AppendFormat("%{0:x2}", c);
            }
            return sb.ToString();
        }

        public string LoadData(string url)
        {
            string rel = "";
            try
            {
                HttpWebRequest hwr = (HttpWebRequest)WebRequest.Create(url);
                hwr.Method = "GET";
                hwr.KeepAlive = true;
                hwr.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
                hwr.Headers.Add("Accept-Charset", "GBK,utf-8;q=0.7,*;q=0.3");
                hwr.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.83 Safari/537.1";
                hwr.Headers.Add("Accept-Language", "zh-CN,zh;q=0.8");
                //hwr.Host = "emoney.cenwave.com";
                if (sessionId != "")
                {
                    //hwr.Headers.Add("Cookie", "ASPSESSIONIDQQDSAQCB=HBIKFNKAMCNEOJGMNKBKDHFO");
                    hwr.Headers.Add("Cookie", sessionkey + "=" + sessionId);
                }
                //hwr.Referer = "";
                hwr.ServicePoint.Expect100Continue = true;
                hwr.Referer = url;
                HttpWebResponse response = (HttpWebResponse)hwr.GetResponse();
                System.IO.Stream myResponseStreame = response.GetResponseStream();
                System.IO.StreamReader sdr = new System.IO.StreamReader(myResponseStreame, Encoding.GetEncoding("utf-8"));
                rel = sdr.ReadToEnd().ToString();
                var strCookie = response.Headers["Set-Cookie"];
                GetCookieValue(strCookie);
            }
            catch (Exception ex)
            {
                sessionkey = "";
                sessionId = "";
            }
            return rel;
        }

        public string GetCookieValue(string strCookie)
        {
            if (string.IsNullOrEmpty(strCookie))
            {
                return string.Empty;
            }
            strCookie = strCookie.Replace("; path=/", "");
            var lst = strCookie.Split(';');
            foreach (var c in lst)
            {
                var tkey = c.Split('=');
                if (tkey.Length > 0)
                {
                    sessionkey = tkey[0];
                    sessionId = tkey[1];
                }
            }
            return string.Empty;
        }

        public string NoHTML(string Htmlstring)
        {
            //删除脚本
            Htmlstring = Regex.Replace(Htmlstring, @"<script[^>]*?>.*?</script>", "",
              RegexOptions.IgnoreCase);
            //删除HTML
            Htmlstring = Regex.Replace(Htmlstring, @"<(.[^>]*)>", "",
              RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"([\r\n])[\s]+", "@",
              RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"-->", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"<!--.*", "", RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(quot|#34);", "\"",
              RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(amp|#38);", "&",
              RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(lt|#60);", "<",
              RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(gt|#62);", ">",
              RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(nbsp|#160);", "   ",
              RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(iexcl|#161);", "\xa1",
              RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(cent|#162);", "\xa2",
              RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(pound|#163);", "\xa3",
              RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&(copy|#169);", "\xa9",
              RegexOptions.IgnoreCase);
            Htmlstring = Regex.Replace(Htmlstring, @"&#(\d+);", "",
              RegexOptions.IgnoreCase);

            Htmlstring = Htmlstring.Replace("<", "");
            Htmlstring = Htmlstring.Replace(">", "");
            Htmlstring = Htmlstring.Replace("\r\n", "");

            //Htmlstring = HttpContext.Current.Server.HtmlEncode(Htmlstring).Trim();
            Htmlstring = Htmlstring.Replace(" ", "");
            Htmlstring = Htmlstring.Substring(1, Htmlstring.Length - 2);
            return Htmlstring;
        }
    }
}